<template>
  <div class="login">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      size="large"
      @keyup.enter.native="handleLogin(ruleFormRef)"
    >
      <el-form-item prop="username">
        <el-input v-model="ruleForm.username" :placeholder="t('login.userPlaceholder')" clearable prefix-icon="user" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="ruleForm.password" :placeholder="t('login.PWPlaceholder')" clearable prefix-icon="lock"
                  show-password />
      </el-form-item>
      <el-form-item class="captcha-item" prop="captcha">
        <el-input v-model="ruleForm.captcha" clearable placeholder="请输入验证码" prefix-icon="lock" />
        <el-image :src="captchaUrl" @click="getCaptchaImage"></el-image>
      </el-form-item>
<!--t('login.rememberPassword')-->
      <div class="login-operate">
        <el-checkbox :label="rememberPassword" v-model="rememberPassword" />
        <el-button link>{{ t("login.forgetPassword") }}?</el-button>
      </div>
      <el-button :loading="isLoading" class="login-btn" type="primary" @click="handleLogin(ruleFormRef)">
        {{ t("login.signIn") }}
      </el-button>
      <!--    <router-link to="/about">跳转</router-link>-->
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { useI18n } from 'vue-i18n'

const { t } = useI18n({
  inheritLocale: true, // 继承全局 locale
  useScope: 'global'   // 使用全局翻译资源
})
import { ComponentInternalInstance, getCurrentInstance, nextTick, onBeforeMount, reactive, ref } from "vue";
import { ComponentSize, ElMessage, FormInstance, FormRules } from "element-plus";
import { captchaImage, loginByJson } from "@/api/login";
import { useLoginAction }  from "@/hooks/useLoginAction"
import { Encrypt } from "@/utils/aes";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface RuleForm {
  username: string;
  password: string;
  key: string;
  captcha: string;
}

let captchaUrl = ref<string>("");
const isLoading = ref<boolean>(false);
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  username: "",
  password: "",
  key: "",
  captcha: ""
});

const locationOptions = ["Home", "Company", "School"];

let rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" }
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" }
  ]
});
// 获取验证码
const getCaptchaImage = async () => {
  // console.log(rules.username[0].message);
  const key: string = new Date().getTime().toString();
  ruleForm.key = key;
  let res = await captchaImage({ key });
  let blob = new Blob([res], { type: "application/vnd.ms-excel" });
  captchaUrl.value = URL.createObjectURL(blob);
};

// 登录
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      isLoading.value = true;
      if (rememberPassword.value){
        localStorage.setItem("rememberPassword",JSON.stringify(rememberPassword.value) );
        userInfo.value = {
          username: ruleForm.username,
          password: ruleForm.password
        }
        localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
      } else {
        localStorage.removeItem("rememberPassword");
      }
      let res: any = await loginByJson({
        password: Encrypt(ruleForm.password),//密码（需要使用AES加密）
        username: Encrypt(ruleForm.username),//用户名（需要使用AES加密）
        key: ruleForm.key,//图形验证码中随机UUID
        captcha: ruleForm.captcha//验证码
      });
      if (res.code != 200) {
        isLoading.value = false;
        ElMessage.error(res.msg);
      } else {
        isLoading.value = false;
        useLoginAction(res.data)
      }
    } else {
      ElMessage.warning("请填写正确的用户名、密码！");
      await getCaptchaImage();
    }
  });
};
onBeforeMount(() => {
  rules = reactive<FormRules<RuleForm>>({
    username: [
      { required: true, message: t("login.userError"), trigger: "blur" }
    ],
    password: [
      { required: true, message: t("login.PWError"), trigger: "blur" }
    ],
    captcha: [
      { required: true, message: "请输入验证码", trigger: "blur" }
    ]
  });
  getCaptchaImage();
  if (rememberPassword.value) {
    ruleForm.username = Encrypt(JSON.parse(localStorage.getItem("userInfo") || "{}").username);
    ruleForm.password = Encrypt(JSON.parse(localStorage.getItem("userInfo") || "{}").password);
  }
  rememberPassword.value = JSON.parse(localStorage.getItem("rememberPassword") || "false");
});
// 记住密码
const rememberPassword = ref<boolean>(false);
const userInfo = ref({})
</script>
<style lang="scss" scoped>
.login {
  height: 300px;

  .captcha-item {

    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-input {
      width: 70%;
      margin-right: 10px;
    }

    .el-image {
      width: 25%;
      height: 40px;
      cursor: pointer;
    }
  }

  .login-operate {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
  }

  .login-btn {
    width: 100%;
    height: 40px;
    border-radius: 20px;
  }
}
</style>
